package com.math.aistudykbr.utils;

import lombok.extern.slf4j.Slf4j;
import org.xmind.core.*;
import org.xmind.core.io.ByteArrayStorage;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.CubicCurve2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;

@Slf4j
public class XmindImageConverter {
    private static final int NODE_HORIZONTAL_GAP = 300;  // 显著增加水平间距
    private static final int NODE_VERTICAL_GAP = 100;    // 增加垂直间距
    private static final int ROOT_FONT_SIZE = 24;       // 更大的根节点字体
    private static final int NODE_FONT_SIZE = 18;       // 更大的普通节点字体
    private static final Color BACKGROUND_COLOR = new Color(252, 252, 252);
    private static final Color NODE_BACKGROUND = new Color(255, 255, 255);
    private static final Color LINE_COLOR = new Color(64, 64, 64);
    private static final Color TEXT_COLOR = new Color(33, 33, 33);
    private static final Color ROOT_BACKGROUND = new Color(240, 247, 255);
    
    public static boolean convertToImage(File xmindFile, String outputPath) {
        try {
            IWorkbookBuilder builder = Core.getWorkbookBuilder();
            IWorkbook workbook = builder.loadFromPath("D:\\Project\\AIStudyKBR\\resource-xmind\\111.xmind", new ByteArrayStorage(), null);
            
            List<ISheet> sheets = workbook.getSheets();
            if (sheets.isEmpty()) {
                log.error("XMind文件中没有找到画布");
                return false;
            }
            
            ISheet primarySheet = sheets.get(0);
            ITopic rootTopic = primarySheet.getRootTopic();
            
            // 增加画布尺寸
            Dimension totalSize = calculateMapDimension(rootTopic, true);
            int width = (int) totalSize.getWidth() + 800;  // 大幅增加边距
            int height = (int) totalSize.getHeight() + 600;
            
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = image.createGraphics();
            
            // 设置最高品质渲染
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
            g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
            
            // 填充背景
            g2d.setColor(BACKGROUND_COLOR);
            g2d.fillRect(0, 0, width, height);
            
            // 从中心点开始绘制
            drawTopic(g2d, rootTopic, width/2, height/2, true);
            
            g2d.dispose();
            return ImageIO.write(image, "PNG", new File(outputPath));
            
        } catch (Exception e) {
            log.error("转换XMind文件到图片时发生错误", e);
            return false;
        }
    }
    
    private static Dimension calculateMapDimension(ITopic topic, boolean isRoot) {
        FontMetrics metrics = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB)
            .createGraphics()
            .getFontMetrics(new Font("微软雅黑", Font.PLAIN, isRoot ? ROOT_FONT_SIZE : NODE_FONT_SIZE));
            
        int width = metrics.stringWidth(topic.getTitleText()) + 80;  // 增加节点内边距
        int height = metrics.getHeight() + 40;
        
        List<ITopic> children = topic.getAllChildren();
        if (!children.isEmpty()) {
            int totalChildWidth = 0;
            int maxChildHeight = 0;
            
            for (ITopic child : children) {
                Dimension childDim = calculateMapDimension(child, false);
                totalChildWidth += childDim.width;
                maxChildHeight = Math.max(maxChildHeight, childDim.height);
            }
            
            totalChildWidth += NODE_HORIZONTAL_GAP * (children.size() - 1);
            width = Math.max(width, totalChildWidth);
            height += maxChildHeight + NODE_VERTICAL_GAP;
        }
        
        return new Dimension(width, height);
    }
    
    private static void drawTopic(Graphics2D g2d, ITopic topic, int x, int y, boolean isRoot) {
        String title = topic.getTitleText();
        Font font = new Font("微软雅黑", isRoot ? Font.BOLD : Font.PLAIN, isRoot ? ROOT_FONT_SIZE : NODE_FONT_SIZE);
        g2d.setFont(font);
        
        FontMetrics metrics = g2d.getFontMetrics();
        int width = metrics.stringWidth(title) + 80;
        int height = metrics.getHeight() + 40;
        
        // 绘制节点阴影
        g2d.setColor(new Color(0, 0, 0, 20));
        g2d.fillRoundRect(x - width/2 + 4, y - height/2 + 4, width, height, 25, 25);
        
        // 绘制节点背景
        Color topColor = isRoot ? ROOT_BACKGROUND : NODE_BACKGROUND;
        Color bottomColor = new Color(topColor.getRed(), topColor.getGreen(), topColor.getBlue(), 240);
        GradientPaint gradient = new GradientPaint(
            x - width/2, y - height/2, topColor,
            x + width/2, y + height/2, bottomColor
        );
        g2d.setPaint(gradient);
        g2d.fillRoundRect(x - width/2, y - height/2, width, height, 25, 25);
        
        // 绘制边框
        g2d.setColor(new Color(LINE_COLOR.getRed(), LINE_COLOR.getGreen(), LINE_COLOR.getBlue(), 180));
        g2d.setStroke(new BasicStroke(isRoot ? 2.5f : 2.0f));
        g2d.drawRoundRect(x - width/2, y - height/2, width, height, 25, 25);
        
        // 绘制文字
        g2d.setColor(TEXT_COLOR);
        int textX = x - metrics.stringWidth(title)/2;
        int textY = y + metrics.getAscent()/2 - 2;
        g2d.drawString(title, textX, textY);
        
        // 绘制子节点
        List<ITopic> children = topic.getAllChildren();
        if (!children.isEmpty()) {
            int totalWidth = 0;
            for (ITopic child : children) {
                Dimension childDim = calculateMapDimension(child, false);
                totalWidth += childDim.width;
            }
            totalWidth += NODE_HORIZONTAL_GAP * (children.size() - 1);
            
            int startX = x - totalWidth/2;
            for (ITopic child : children) {
                Dimension childDim = calculateMapDimension(child, false);
                int childX = startX + childDim.width/2;
                int childY = y + NODE_VERTICAL_GAP + height/2 + 30;
                
                // 绘制贝塞尔曲线连接线
                drawCurvedConnection(g2d, x, y + height/2, childX, childY - height/2);
                
                // 绘制子节点
                drawTopic(g2d, child, childX, childY, false);
                
                startX += childDim.width + NODE_HORIZONTAL_GAP;
            }
        }
    }
    
    private static void drawCurvedConnection(Graphics2D g2d, int x1, int y1, int x2, int y2) {
        g2d.setColor(new Color(LINE_COLOR.getRed(), LINE_COLOR.getGreen(), LINE_COLOR.getBlue(), 160));
        g2d.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        
        // 使用三次贝塞尔曲线
        int ctrlX1 = x1;
        int ctrlY1 = y1 + (y2 - y1) / 3;
        int ctrlX2 = x2;
        int ctrlY2 = y2 - (y2 - y1) / 3;
        
        g2d.draw(new CubicCurve2D.Float(x1, y1, ctrlX1, ctrlY1, ctrlX2, ctrlY2, x2, y2));
    }
}